/**
 * 2019年2月17日下午1:08:49
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.dao.MySqlRedisDao;

import redis.clients.jedis.Jedis;

/**
 * @author whati
 *
 */
@Service
public class MySqlRedisService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(MySqlRedisService.class);
	@Autowired
	private MySqlRedisDao dao;
	private Jedis jedis = RedisKit.getJedis();
	public String startFromMysqlToRedis() {
		logger.info("开始从mysql同步到redis");
		//1.将房源进行同步
		List<Record> list = dao.queryForRecordList("select * from room ");
		String jsonList = JsonKit.listToJson(list, 1);
		JSONArray jsonArray = JSON.parseArray(jsonList);
		int size = jsonArray.size();
		Map<String,String> roomMap= new HashMap<String,String>();
		for(int i=0;i<size;i++) {
			JSONObject jsonObj = jsonArray.getJSONObject(i);
			roomMap.put(jsonObj.getString("D_ID"), JSON.toJSONString(jsonObj));
		}
		jedis.hmset("rooms", roomMap);
		//2.将用户进行同步
		List<Record> userlist = dao.queryForRecordList("select * from t_user ");
		String userJsonList = JsonKit.listToJson(userlist, 1);
		logger.info(userJsonList);
		JSONArray userJsonArray = JSON.parseArray(userJsonList);
		int userSize = userJsonArray.size();
		Map<String,String> userMap= new HashMap<String,String>();
		for(int i=0;i<userSize;i++) {
			JSONObject jsonObj = userJsonArray.getJSONObject(i);
			userMap.put(jsonObj.getString("D_Tel"), JSON.toJSONString(jsonObj));
		}
		jedis.hmset("users", userMap);
		//3.将内控房源进行同步
		List<Record> nkRoomlist = dao.queryForRecordList("select * from room where D_Monitor=1");
		String nkRoomJson = JsonKit.listToJson(nkRoomlist, 1);
		JSONArray nkJsonArray = JSON.parseArray(nkRoomJson);
		int nkSize = nkJsonArray.size();
		Map<String,String> nkRoomMap= new HashMap<String,String>();
		for(int i=0;i<nkSize;i++) {
			JSONObject jsonObj = nkJsonArray.getJSONObject(i);
			nkRoomMap.put(jsonObj.getString("D_ID"), JSON.toJSONString(jsonObj));
		}
		jedis.hmset("nkRooms", nkRoomMap);//会有删除操作，单个翻红之后，要删除这个房源，防止在一键翻红时再被处理。
		return "";
	}
	
	public String overFromRedisToMysql() {
		//1.将房源同步到redis
		List<String> list = jedis.hvals("rooms");
		dao.batchUpdateFangYuanList(list);
		//2.用户收藏表同步
		List<Record> recList = new ArrayList<Record>();
		List<String> userScList = jedis.hvals("userShouCang");
		for(int i=0;i<userScList.size();i++) {
			String scJson = jedis.hmget("userShouCang", userScList.get(i)).get(0);
			if(StrKit.isNotEmpty(scJson)) {
				Record rec = new Record();
				if(scJson.contains(",")) {
					String[] fieldIds = scJson.split(",");
					for(int k=0;k<fieldIds.length;k++) {
						rec.set("UserName", userScList.get(i));
						rec.set("FieldId", fieldIds[k]);
						rec.set("Sort", k+1);
						recList.add(rec);
					}
				}else {
					rec.set("userName", userScList.get(i));
					rec.set("FieldId", scJson);
					rec.set("Sort", 1);
					recList.add(rec);
				}
			}
		}
		dao.batchInsertUserCollectionList(recList);
		
		return "";
	}
	
	public static List<Record> queryForRecordList(String sql){
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-jdbc.xml");
		JdbcTemplate  jdbcTemplate = context.getBean("jdbcTemplate",JdbcTemplate.class);
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
		// System.err.println(result.size());
		List<Record> recordList = new ArrayList<Record>();
		for (Map<String, Object> map : result) {
			// System.err.println((String)map.get("D_BanName"));
			recordList.add(new Record(map));
		}
		return recordList;
	}
	public static List<Record> queryForUserRecordList(String sql){
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-jdbc.xml");
		JdbcTemplate  jdbcTemplate = context.getBean("jdbcTemplate",JdbcTemplate.class);
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
		// System.err.println(result.size());
		List<Record> recordList = new ArrayList<Record>();
		for (Map<String, Object> map : result) {
			// System.err.println((String)map.get("D_BanName"));
			recordList.add(new Record(map));
		}
		return recordList;
	}
	public static void main(String[] args) {
		Jedis jedis = RedisKit.getJedis();	
		//房源mysql同步到redis
		/*List<Record> list = MySqlRedisService.queryForRecordList("select * from room ");
		String jsonList = JsonKit.listToJson(list, 1);
		JSONArray jsonArray = JSON.parseArray(jsonList);
		int size = jsonArray.size();
		Map<String,String> roomMap= new HashMap<String,String>();
		for(int i=0;i<size;i++) {
			JSONObject jsonObj = jsonArray.getJSONObject(i);
			roomMap.put(jsonObj.getString("D_ID"), JSON.toJSONString(jsonObj));
		}
		jedis.hmset("rooms", roomMap);*/
		/*String jsonStr = jedis.hvals("rooms").get(0);//jedis.hmget("rooms", "1003").get(0);
		JSONObject jsonObj = JSON.parseObject(jsonStr);
		System.err.println(jsonObj.getString("d_position"));*/
		List<Record> userlist =  MySqlRedisService.queryForRecordList("select * from t_user ");
		String userJsonList = JsonKit.listToJson(userlist, 1);
		logger.info(userJsonList);
		JSONArray userJsonArray = JSON.parseArray(userJsonList);
		int userSize = userJsonArray.size();
		Map<String,String> userMap= new HashMap<String,String>();
		for(int i=0;i<userSize;i++) {
			JSONObject jsonObj = userJsonArray.getJSONObject(i);
			userMap.put(jsonObj.getString("D_Tel"), JSON.toJSONString(jsonObj));
		}
		jedis.hmset("users", userMap);
	}
}
